package me.pearjelly.filters.commons;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import me.pearjelly.filters.VisitFilter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import edu.uci.ics.crawler4j.url.WebURL;

public class ResetUrlFilter implements VisitFilter {
	private static final Logger logger = LoggerFactory
			.getLogger(ResetUrlFilter.class);
	private Pattern pattern;
	private VisitFilter nextVisitFilter;

	public ResetUrlFilter() {
	}

	public ResetUrlFilter(String resetReg, VisitFilter visitFilter) {
		this.pattern = Pattern.compile(resetReg);
		this.nextVisitFilter = visitFilter;
	}

	@Override
	public boolean filter(WebURL webURL) {
		String url = webURL.getURL().toLowerCase();
		try {			
			Matcher matcher = this.pattern.matcher(url);
			if (matcher.matches()) {
				String newUrl = matcher.group(1);
				if (newUrl != null && newUrl.trim().length() > 0
						&& newUrl.startsWith("http://")) {
					webURL.setURL(newUrl);
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			webURL.setURL(url);
		}
		return (null == nextVisitFilter || nextVisitFilter.filter(webURL));
	}

}
